﻿using UnityEngine;
using UnityEngine.UI;

namespace WoogiUI
{
    internal sealed class WoogiCanvas : WoogiGameObject
    {
        private bool isRegist;
        public bool isUseUICamera = true;
        #region 
        internal void Regist()
        {
            isRegist = true;
            gameObject.name = gameObject.name.Replace("(Clone)", "");
            UIManager.Instance.RegisterCanvas(gameObject.name, this);
        }

        void OnDestroy()
        {
            UIManager.Instance.DestroyCanvas(gameObject.name, true);
        }
        #endregion

        void Awake()
        {
            CheckPlaneRegist();
            if (!isRegist)
                Regist();

        }

        void Start()
        {
            if (UICamera.Instance.IsOpenUICamera && isUseUICamera)
            {
                Canvas canvas = GetComponent<Canvas>();
                canvas.renderMode = RenderMode.ScreenSpaceCamera;
                Camera uiCamera = UICamera.Instance.UiCamera;
                canvas.worldCamera = uiCamera;
                canvas.planeDistance = 20f;
                CanvasScaler canvasScaler = canvas.GetComponent<CanvasScaler>();
                canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
                canvasScaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
                canvasScaler.matchWidthOrHeight = 0f;
            }
        }

        public int GetSortLayer
        {
            get
            {
                return GetComponent<Canvas>().sortingOrder;
            }
            set
            {
                GetComponent<Canvas>().sortingOrder = value;
            }
        }

        private void CheckPlaneRegist()
        {
            if (transform.childCount > 0)
            {
                foreach (Transform childTf in transform)
                {
                    WoogiPlane plane = childTf.GetComponent<WoogiPlane>();
                    if (plane != null)
                    {
                        plane.Regist();
                    }
                }
            }
        }
    }
}


